//
//  ShouXinVC.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/27.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView



class ShouXinVC: UIViewController {
    
    @IBOutlet weak var topLabel: UILabel!
    @IBOutlet weak var imgView: UIImageView!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var priceLabel: UILabel!
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var warningLabel: UILabel!
    
    var alertBottomButton: SCLButton!
    var date: String!

    override func viewDidLoad() {
        super.viewDidLoad()
        let item = UIBarButtonItem(title: "设置", style: .plain, target: self, action: #selector(itemBtTapped(_:)))
        navigationItem.setRightBarButton(item, animated: true)
    }
    
    @objc func itemBtTapped(_ button: UIBarButtonItem!) {
        let appearance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: false, hideWhenBackgroundViewIsTapped: true)
        let dateAlert = SCLAlertView(appearance: appearance)
        let textField = dateAlert.addTextField("金额")
        textField.keyboardType = .numberPad
        textField.placeholder = "请填写授信金额"
        alertBottomButton = dateAlert.addButton("点击设置授信日期", target: self, selector: #selector(alertBottomBtTapped(_:)))
        dateAlert.addButton("确定", action: {
            guard let price = textField.text.nilIfEmpty else {
                return
            }
            guard let dt = self.date else {
                return
            }
            let jsonString = "Credit:{\"date\":\"\(dt)\",\"limit\":\"\(price)\",\"lendStoreId\":\(Store.storeId!)}"
            guard let stringEncoding = jsonString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
                return
            }
            print(stringEncoding)
            guard let image = self.generateQRCode(from: stringEncoding) else {
                return
            }
            self.stackView.isHidden = false
            self.warningLabel.isHidden = true
            self.imgView.image = image
            self.dateLabel.text = self.date
            self.priceLabel.text = "¥ "+price
            dateAlert.hideView()
        })
        dateAlert.showNotice("设置授信内容", subTitle: "")
    }
    @objc func alertBottomBtTapped(_ button: SCLButton!) {
        DatePickerDialog().show("点击设置授信日期", doneButtonTitle: "完成", cancelButtonTitle: "关闭", defaultDate: Date(), minimumDate: Date(timeIntervalSince1970: 0), maximumDate: Date(timeIntervalSinceNow: 0), datePickerMode: .date) { (date) in
            if let dt = date {
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyy-MM-dd"
                self.alertBottomButton.setTitle("授信日期：\(formatter.string(from: dt))", for: .normal)
                self.date = formatter.string(from: dt)
            }
        }
    }
}
